package com.hzyl.famousreader.view.fragment;


import android.arch.lifecycle.Observer;
import android.arch.lifecycle.ViewModelProviders;
import android.content.Context;
import android.content.res.Configuration;
import android.databinding.DataBindingUtil;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.CompoundButton;
import android.widget.Toast;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.blankj.utilcode.util.BarUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.SPUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.hzyl.famousreader.Constant;
import com.hzyl.famousreader.R;
import com.hzyl.famousreader.ThemeColor;
import com.hzyl.famousreader.repository.cache.AdCache;
import com.hzyl.famousreader.repository.persistence.entity.Ad;
import com.hzyl.famousreader.repository.webservice.RetrofitClient;
import com.hzyl.famousreader.repository.webservice.api.AdService;
import com.hzyl.famousreader.repository.webservice.cache.Resource;
import com.hzyl.famousreader.repository.webservice.model.PageWrapper;
import com.hzyl.famousreader.repository.webservice.model.Result;
import com.hzyl.famousreader.router.Router;
import com.hzyl.famousreader.view.adapter.AdAdapter;
import com.hzyl.famousreader.viewmodel.AdViewModel;
import com.hzyl.famousreader.databinding.*;
import com.qq.e.ads.ContentAdType;
import com.qq.e.ads.cfg.VideoOption;
import com.qq.e.ads.nativ.ADSize;
import com.qq.e.ads.nativ.MediaListener;
import com.qq.e.ads.nativ.MediaView;
import com.qq.e.ads.nativ.NativeExpressAD;
import com.qq.e.ads.nativ.NativeExpressADView;
import com.qq.e.ads.nativ.NativeExpressMediaListener;
import com.qq.e.ads.nativ.NativeMediaADData;
import com.qq.e.comm.constants.AdPatternType;
import com.qq.e.comm.pi.AdData;
import com.qq.e.comm.util.AdError;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import static com.tencent.smtt.sdk.TbsReaderView.TAG;

/**
 * 发现
 */
@Route(path = "/main/discovery")
public class DiscoveryFragment extends BaseFragment implements NativeExpressAD.NativeExpressADListener{

  private FragmentDiscoveryBinding binding;

  /**
   * 分页参数：第几页
   */
  private int pi = 1;

  /**
   * 分页参数：展示的数量
   */
  private int ps = 10;

  private long total = 1000;

  private AdAdapter adAdapter;

  private AdCache adCache;

  private AdViewModel adViewModel;

//  ad
  private NativeExpressADView nativeExpressADView;
  private NativeExpressAD nativeExpressAD;

  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container,
                           Bundle savedInstanceState) {

    super.onCreateView(inflater, container, savedInstanceState);

    binding = DataBindingUtil.inflate(inflater, R.layout.fragment_discovery, container, false);

    int colorId = SPUtils.getInstance().getInt(Constant.SP_THEME_COLOR,  ThemeColor.DEFAULT.getColor());
    BarUtils.setStatusBarColor(getActivity(), colorId, 0);
    binding.toolbar.setBackgroundColor(colorId);

    adViewModel = ViewModelProviders.of(this).get(AdViewModel.class);

    adCache = new AdCache();

    adAdapter = new AdAdapter(null);
    adAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
      @Override
      public void onLoadMoreRequested() {
        if (pi * ps > total) {
          adAdapter.loadMoreEnd();
        } else {
          AdService adService = RetrofitClient.getInstance().create(AdService.class);
          adService.getDiscoveryAds(pi, ps).enqueue(new Callback<Result<PageWrapper<Ad>>>() {
            @Override
            public void onResponse(Call<Result<PageWrapper<Ad>>> call, Response<Result<PageWrapper<Ad>>> response) {
              Result<PageWrapper<Ad>> result = response.body();
              if (result.getErrno() == Result.SUCCESS_ERRNO) {
                PageWrapper<Ad> pageWrapper = result.getData();
                total = pageWrapper.getTotal();
                pi++;
                adAdapter.addData(pageWrapper.getList());
              } else if (result.getErrno() == Result.ERROR_ERRNO) {
                LogUtils.d("操作失败啦啦啦啦啦啦");
              }
              adAdapter.loadMoreComplete();
            }

            @Override
            public void onFailure(Call<Result<PageWrapper<Ad>>> call, Throwable t) {
              LogUtils.d("获取发现板块的广告时出现异常了");
              adAdapter.loadMoreFail();
            }
          });
        }
      }
    }, binding.discoveryRvAd);
    adAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
      @Override
      public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        List<Ad> ads = adapter.getData();
        String url = ads.get(position).getUrl();
        ARouter.getInstance().build(Router.ACTIVITY_WEB).withString("url", url).navigation(getActivity());
      }
    });

    binding.discoveryRvAd.setLayoutManager(new LinearLayoutManager(getContext()));
    binding.discoveryRvAd.setAdapter(adAdapter);

    //获取缓存的广告
    adViewModel.adDiscovery().observe(this, new Observer<Resource<PageWrapper<Ad>>>() {
      @Override
      public void onChanged(@Nullable Resource<PageWrapper<Ad>> listResource) {
        PageWrapper<Ad> pageWrapper = listResource.data;
        if(pageWrapper != null) {
          adAdapter.setNewData(pageWrapper.getList());
          total = pageWrapper.getTotal();
        }
      }
    });


//    My m = new My(this.getContext());
//    m.initData(binding.discoveryLvAd);
      refreshAd();
//    binding.discoveryLvAd.se
    return binding.getRoot();
  }

  private void refreshAd() {
    try {

      /**
       *  如果选择支持视频的模版样式，请使用{@link PositionId#NATIVE_EXPRESS_SUPPORT_VIDEO_POS_ID}
       */
      nativeExpressAD = new NativeExpressAD(getContext(), getMyADSize(),Constant.TX_APPID,Constant.TX_NAVPOSID, this); // 这里的Context必须为Activity
      nativeExpressAD.setVideoOption(new VideoOption.Builder()
        .setAutoPlayPolicy(VideoOption.AutoPlayPolicy.ALWAYS) // 设置什么网络环境下可以自动播放视频
        .setAutoPlayMuted(true) // 设置自动播放视频时，是否静音
        .build()); // setVideoOption是可选的，开发者可根据需要选择是否配置
      nativeExpressAD.setMaxVideoDuration(0);
      /**
       * 如果广告位支持视频广告，强烈建议在调用loadData请求广告前调用setVideoPlayPolicy，有助于提高视频广告的eCPM值 <br/>
       * 如果广告位仅支持图文广告，则无需调用
       */

      /**
       * 设置本次拉取的视频广告，从用户角度看到的视频播放策略<p/>
       *
       * "用户角度"特指用户看到的情况，并非SDK是否自动播放，与自动播放策略AutoPlayPolicy的取值并非一一对应 <br/>
       *
       * 如自动播放策略为AutoPlayPolicy.WIFI，但此时用户网络为4G环境，在用户看来就是手工播放的
       */
      nativeExpressAD.setVideoPlayPolicy(getVideoPlayPolicy(VideoOption.AutoPlayPolicy.ALWAYS, getContext()));  // 本次拉回的视频广告，在用户看来是否为自动播放的
      nativeExpressAD.loadAD(1);
    } catch (NumberFormatException e) {
      Log.w(TAG, "ad size invalid.");
    }
  }

  private ADSize getMyADSize() {
    int w = ADSize.FULL_WIDTH;
    int h = ADSize.AUTO_HEIGHT;
    return new ADSize(w, h);
  }

  public static int getVideoPlayPolicy(int autoPlayPolicy, Context context){
    if(autoPlayPolicy == VideoOption.AutoPlayPolicy.ALWAYS){
      return VideoOption.VideoPlayPolicy.AUTO;
    }else if(autoPlayPolicy == VideoOption.AutoPlayPolicy.WIFI){
      ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
      NetworkInfo wifiNetworkInfo = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
      return wifiNetworkInfo != null && wifiNetworkInfo.isConnected() ? VideoOption.VideoPlayPolicy.AUTO
        : VideoOption.VideoPlayPolicy.MANUAL;
    }else if(autoPlayPolicy == VideoOption.AutoPlayPolicy.NEVER){
      return VideoOption.VideoPlayPolicy.MANUAL;
    }
    return VideoOption.VideoPlayPolicy.UNKNOWN;
  }


  /**
   * 获取广告数据
   *
   * @param nativeExpressADView
   * @return
   */
  private String getAdInfo(NativeExpressADView nativeExpressADView) {
    AdData adData = nativeExpressADView.getBoundData();
    if (adData != null) {
      StringBuilder infoBuilder = new StringBuilder();
      infoBuilder.append("title:").append(adData.getTitle()).append(",")
        .append("desc:").append(adData.getDesc()).append(",")
        .append("patternType:").append(adData.getAdPatternType());
      if (adData.getAdPatternType() == AdPatternType.NATIVE_VIDEO) {
        infoBuilder.append(", video info: ").append(getVideoInfo(adData.getProperty(AdData.VideoPlayer.class)));
      }
      Log.d(TAG, "eCPM = " + adData.getECPM() + " , eCPMLevel = " + adData.getECPMLevel());
      return infoBuilder.toString();
    }
    return null;
  }

  private String getVideoInfo(AdData.VideoPlayer videoPlayer) {
    if (videoPlayer != null) {
      StringBuilder videoBuilder = new StringBuilder();
      videoBuilder.append("{state:").append(videoPlayer.getVideoState()).append(",")
        .append("duration:").append(videoPlayer.getDuration()).append(",")
        .append("position:").append(videoPlayer.getCurrentPosition()).append("}");
      return videoBuilder.toString();
    }
    return null;
  }


  @Override
  public void onADLoaded(List<NativeExpressADView> adList) {
    Log.i(TAG, "onADLoaded: " + adList.size());
    // 释放前一个展示的NativeExpressADView的资源
    if (nativeExpressADView != null) {
      nativeExpressADView.destroy();
    }

//    if (container.getVisibility() != View.VISIBLE) {
//      container.setVisibility(View.VISIBLE);
//    }
//
//    if (container.getChildCount() > 0) {
//      container.removeAllViews();
//    }

    nativeExpressADView = adList.get(0);
    Log.i(TAG, "onADLoaded, video info: " + getAdInfo(nativeExpressADView));
    if (nativeExpressADView.getBoundData().getAdPatternType() == AdPatternType.NATIVE_VIDEO) {
      nativeExpressADView.setMediaListener(mediaListener);
    }
    // 广告可见才会产生曝光，否则将无法产生收益。
    binding.discoveryLvAd.addView(nativeExpressADView);
    nativeExpressADView.render();
  }

  private NativeExpressMediaListener mediaListener = new NativeExpressMediaListener() {
    @Override
    public void onVideoInit(NativeExpressADView nativeExpressADView) {
      Log.i(TAG, "onVideoInit: "
        + getVideoInfo(nativeExpressADView.getBoundData().getProperty(AdData.VideoPlayer.class)));
    }

    @Override
    public void onVideoLoading(NativeExpressADView nativeExpressADView) {
      Log.i(TAG, "onVideoLoading");
    }

    @Override
    public void onVideoReady(NativeExpressADView nativeExpressADView, long l) {
      Log.i(TAG, "onVideoReady");
    }

    @Override
    public void onVideoStart(NativeExpressADView nativeExpressADView) {
      Log.i(TAG, "onVideoStart: "
        + getVideoInfo(nativeExpressADView.getBoundData().getProperty(AdData.VideoPlayer.class)));
    }

    @Override
    public void onVideoPause(NativeExpressADView nativeExpressADView) {
      Log.i(TAG, "onVideoPause: "
        + getVideoInfo(nativeExpressADView.getBoundData().getProperty(AdData.VideoPlayer.class)));
    }

    @Override
    public void onVideoComplete(NativeExpressADView nativeExpressADView) {
      Log.i(TAG, "onVideoComplete: "
        + getVideoInfo(nativeExpressADView.getBoundData().getProperty(AdData.VideoPlayer.class)));
    }

    @Override
    public void onVideoError(NativeExpressADView nativeExpressADView, AdError adError) {
      Log.i(TAG, "onVideoError");
    }

    @Override
    public void onVideoPageOpen(NativeExpressADView nativeExpressADView) {
      Log.i(TAG, "onVideoPageOpen");
    }

    @Override
    public void onVideoPageClose(NativeExpressADView nativeExpressADView) {
      Log.i(TAG, "onVideoPageClose");
    }
  };


  @Override
  public void onRenderFail(NativeExpressADView nativeExpressADView) {

  }

  @Override
  public void onRenderSuccess(NativeExpressADView nativeExpressADView) {

  }

  @Override
  public void onADExposure(NativeExpressADView nativeExpressADView) {

  }

  @Override
  public void onADClicked(NativeExpressADView nativeExpressADView) {

  }

  @Override
  public void onADClosed(NativeExpressADView nativeExpressADView) {

  }

  @Override
  public void onADLeftApplication(NativeExpressADView nativeExpressADView) {

  }

  @Override
  public void onADOpenOverlay(NativeExpressADView nativeExpressADView) {

  }

  @Override
  public void onADCloseOverlay(NativeExpressADView nativeExpressADView) {

  }

  @Override
  public void onNoAD(AdError adError) {

  }
}
